package com.huanxing.cloud.security.utils;

import cn.hutool.core.util.StrUtil;
import com.huanxing.cloud.common.core.constant.SecurityConstants;
import com.huanxing.cloud.security.entity.HuanxingUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * spring security工具类
 *
 * @author lijx
 * @date 2022/5/3 18:16
 * @version 1.0
 */
@UtilityClass
public class SecurityUtils {
  /** 获取Authentication */
  public Authentication getAuthentication() {
    return SecurityContextHolder.getContext().getAuthentication();
  }

  /**
   * 获取用户
   *
   * @author lijx
   * @date 2022/5/3 18:15
   * @version 1.0
   */
  public HuanxingUser getUser(Authentication authentication) {
    Object principal = authentication.getPrincipal();
    if (principal instanceof HuanxingUser) {
      return (HuanxingUser) principal;
    }
    return null;
  }

  /** 获取用户 */
  public HuanxingUser getUser() {
    Authentication authentication = getAuthentication();
    return getUser(authentication);
  }

  /**
   * 获取用户角色信息
   *
   * @return 角色集合
   */
  public List<String> getRoles() {
    Authentication authentication = getAuthentication();
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

    List<String> roleIds = new ArrayList<>();
    authorities.stream()
        .filter(granted -> StrUtil.startWith(granted.getAuthority(), SecurityConstants.ROLE))
        .forEach(
            granted -> {
              String id = StrUtil.removePrefix(granted.getAuthority(), SecurityConstants.ROLE);
              roleIds.add(id);
            });
    return roleIds;
  }
}
